package com.distribution.system.controller;

import com.alibaba.fastjson2.JSONObject;
import com.distribution.common.constant.HttpStatus;
import com.distribution.common.core.controller.BaseController;
import com.distribution.common.core.domain.AjaxResult;
import com.distribution.common.core.domain.entity.SysDictData;
import com.distribution.common.core.page.PageDomain;
import com.distribution.common.core.page.TableDataInfo;
import com.distribution.common.core.page.TableSupport;
import com.distribution.common.utils.StringUtils;
import com.distribution.framework.config.ServerConfig;
import com.distribution.system.domain.bo.Recommended;
import com.distribution.system.domain.converter.CmccDaOrderWebConverter;
import com.distribution.system.domain.dto.CmccDaOrderListDTO;
import com.distribution.system.domain.entity.CmccDaBanner;
import com.distribution.system.domain.entity.CmccDaOrder;
import com.distribution.system.domain.entity.CmccDaProduct;
import com.distribution.system.domain.req.CmccDaOrderListReq;
import com.distribution.system.domain.req.CmccDaProductListReq;
import com.distribution.system.domain.req.PublicProductListReq;
import com.distribution.system.service.CmccDaBannerService;
import com.distribution.system.service.CmccDaOrderService;
import com.distribution.system.service.CmccDaProductService;
import com.distribution.system.service.ISysDictTypeService;
import com.distribution.system.utils.http.HttpRequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: GodLu
 * @create: 2024-09-19 11:44
 * @description: 公共接口
 */
@Slf4j
@RestController
@RequestMapping("/public")
public class PublicApiController extends BaseController {
    @Value("${swagger.pathMapping}")
    private String pathMapping;
    @Resource
    ServerConfig serverConfig;
    // APPID
    @Value("${tt.appId}")
    private String appId;
    // 接收结果通知地址
    @Value("${tt.appSecret}")
    private String appSecret;
    @Resource
    CmccDaProductService cmccDaProductService;
    @Resource
    CmccDaBannerService cmccDaBannerService;
    @Resource
    private ISysDictTypeService dictTypeService;
    @Resource
    CmccDaOrderWebConverter cmccDaOrderWebConverter;
    @Resource
    CmccDaOrderService cmccDaOrderService;

    /**
     * 获取推荐商品列表信息
     */
    @PostMapping("/getPublicProductList")
    public TableDataInfo getRecommendedList(@RequestBody PublicProductListReq publicProductListReq) {
        CmccDaProductListReq cmccDaProductListReq = new CmccDaProductListReq();
        BeanUtils.copyProperties(publicProductListReq, cmccDaProductListReq);
        cmccDaProductListReq.setUserId(publicProductListReq.getUserId());
        cmccDaProductListReq.setProductTypeId(publicProductListReq.getProductTypeId());
        cmccDaProductListReq.setPromotionFlag(publicProductListReq.getPromotionFlag());
//        startPage();
        List<Recommended> recommendedList = cmccDaProductService.getRecommendedList(cmccDaProductListReq);
        // 手动分页
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        int begin = pageNum * pageSize - 1;
        int end = Math.min(begin + pageSize, recommendedList.size() - 1);
        rspData.setRows(recommendedList.subList(begin, end));
        rspData.setTotal(recommendedList.size());
        return rspData;
    }

    @PostMapping("/swiperList")
    public AjaxResult swiperList(){
        List<CmccDaBanner> list = cmccDaBannerService.lambdaQuery().eq(CmccDaBanner::getStatus, 1).orderByAsc(CmccDaBanner::getSort).list();
        list.forEach(f -> f.setImgPath(serverConfig.getUrl() + pathMapping + f.getImgPath()));
        return success(list);
    }

    @PostMapping("/getProductByProductCode")
    public AjaxResult getProductByProductCode(@RequestParam String productCode){
        CmccDaProduct product = cmccDaProductService.getByProductCode(productCode);
        product.setMainImagePath(serverConfig.getUrl() + pathMapping + product.getMainImagePath());
        product.setShareImagePath(serverConfig.getUrl() + pathMapping + product.getShareImagePath());
        product.setOriginalCodeImagePath(serverConfig.getUrl() + pathMapping + product.getOriginalCodeImagePath());
        product.setUnorderBgPath(serverConfig.getUrl() + pathMapping + product.getUnorderBgPath());
        return success(product);
    }

    @GetMapping(value = "/getProductTypeList")
    public AjaxResult getProductTypeList()
    {
        List<SysDictData> data = dictTypeService.selectDictDataByType("sys_product_type");
        if (StringUtils.isNull(data))
        {
            data = new ArrayList<SysDictData>();
        }
        return success(data);
    }

    @GetMapping("/getOrderStatusList")
    public AjaxResult getOrderStatusList()
    {
        List<SysDictData> data = dictTypeService.selectDictDataByType("sys_order_status");
        if (StringUtils.isNull(data))
        {
            data = new ArrayList<SysDictData>();
        }
        return success(data);
    }

    @PostMapping("/getTtOpenId")
    public AjaxResult getTtOpenId(@RequestBody String code)
    {
        String url = "https://developer.toutiao.com/api/apps/v2/jscode2session";
        Map<String,String> requestParamMap = new HashMap<>();
        requestParamMap.put("appid", appId);
        requestParamMap.put("secret", appSecret);
        requestParamMap.put("code", code);
        requestParamMap.put("anonymous_code", "");
        JSONObject responseJson = JSONObject.parseObject(HttpRequestUtils.sendPost(url, new JSONObject(requestParamMap).toString()));
        if (responseJson.getInteger("err_no") == 0){
            JSONObject data = responseJson.getJSONObject("data");
            JSONObject returnJson = new JSONObject();
            returnJson.put("openid", data.getString("openid"));
            return success(returnJson);
        }else {
            return error(responseJson.getString("err_tips"));
        }
    }

    @PostMapping("/getOrderStatusCount")
    AjaxResult getOrderStatusCount(@RequestBody CmccDaOrderListReq cmccDaOrderListReq) {
        CmccDaOrderListDTO cmccDaOrderListDTO = cmccDaOrderWebConverter.cmccDaOrderListReqToDto(cmccDaOrderListReq);
        return success(cmccDaOrderService.getOrderStatusCount(cmccDaOrderListDTO));
    }

    @PostMapping("/getOrderList")
    public TableDataInfo getOrderList(@RequestBody CmccDaOrderListReq cmccDaOrderListReq)
    {
        CmccDaOrderListDTO cmccDaOrderListDTO = cmccDaOrderWebConverter.cmccDaOrderListReqToDto(cmccDaOrderListReq);
        startPage();
        List<CmccDaOrder> cmccDaOrders = cmccDaOrderService.listCmccDaOrder(cmccDaOrderListDTO);
        return getDataTable(cmccDaOrders);
    }

    @GetMapping("/getOrderBySearchValue/{searchValue}")
    public AjaxResult getOrderBySearchValue(@PathVariable String searchValue)
    {
        List<CmccDaOrder> orderList = cmccDaOrderService.lambdaQuery()
                .and(q -> q.eq(CmccDaOrder::getCustomerName, searchValue)
                        .or().eq(CmccDaOrder::getCustomerPhone, searchValue)).list();
//        System.out.println("orderList = " + orderList);
        return success(orderList);
    }
}
